<template>
  <ul class="list">
    <li
      v-for="item of letters"
      :key="item"
      :ref="item"
      @click="handleLetterClick"
      @touchstart.prevent="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >{{item}}</li>
  </ul>
</template>
<script>
export default {
  name: "Alphabet",
  props: {
    citys: Object
  },
  data() {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    };
  },
   //当页面挂载完成，startY就不需要重新计算 
  updataed() {
       this.startY = this.$refs["A"][0].getBoundingClientRect().top;
  },
  computed: {
    letters() {
      const letters = [];
      for (let i in this.citys) {
        letters.push(i);
      }
      return letters;
    }
  },
  methods: {
    handleLetterClick: function(e) {
      this.$emit("change", e.target.innerText);
    },
    handleTouchStart() {
      this.touchStatus = true;
    },
    handleTouchMove(e) {
      // const length 字母之间的高度 =   手指划到的高度touchY - 第一个字母 A 距离顶部的高度 startY
      // const index = length /20  总的高度除以20就是分到的等分，也就是当前的字母位置
      // 通过传值的方式将当前的index传递给父组件 
      if (this.touchStatus) {
            if(this.timer){
                clearTimeout(this.timer)
          }
            this.timer = setTimeout(() => {
              const touchY = e.touches[0].clientY;  
              const index = Math.floor((touchY - this.startY ) / 20);
              if (index >= 0 && index < this.letters.length) {
                 this.$emit("change", this.letters[index]);
               }
            },8)
        
      }
    },
    handleTouchEnd() {}
  }
};
</script>
<style lang="stylus" scoped>
@import '~@styles/varibles.styl';

.list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: fixed;
  top: 50%;
  right: 0;
  width: 0.4rem;
  transform: translate(2%, -50%);
}

.list li {
  color: $bgColor;
  line-height: 0.4rem;
}
</style>